<?php
include dirname(dirname(__FILE__)) . '/conf.php';
include SERVER_ROOT . 'public/saetv2.ex.class.php';
require SERVER_ROOT . 'public/validation.php';
require SERVER_ROOT . 'public/ip.php';

$action = get_str('action');
switch ($action){
	case 'getclientip':
		$ip = getclientip();
		output($ip);
		break;

	case 'getarea':
		$ip_domain = get_str('ip_domain');
		if ($ip_domain === false || empty($ip_domain)){
			output('Input Error!');
		}

		if (check_ip($ip_domain)){
			$ip = $ip_domain;
		}else{
			$tmp = parse_url($ip_domain);
			$domain = isset($tmp['host']) ? $tmp['host'] : $ip_domain;
			$ip = gethostbyname($domain);
			if ($domain == $ip){
				output('Domain analysis error!');
			}
		}

		$area = convertip($ip);
		output("IP：" . $ip . " - 位置：" . $area);
		break;

	case 'ip':
		$content = get_str('content', '');
		$re = '';
		if (check_ip($content)){
			$re = ip2long($content);
		}else{
			$re = long2ip($content);
		}
		$re = ($re === false) ? 'Error!' : $re;
		output($re);
		break;

	case 'md5':
		$content = get_str('content', '');
		output(md5($content));
		break;

	case 'serialize':
		$do = get_str('do', 'encode');
		$content = get_str('content', '');
		if ($do == 'encode'){
			output(serialize($content));
		}else{
			output(unserialize($content));
		}
		break;

	case 'json':
		$do = get_str('do', 'encode');
		$content = get_str('content', '');
		if ($do == 'encode'){
			output(json_encode($content));
		}else{
			output(json_decode($content));
		}
		break;

	case 'urlcode':
		$do = get_str('do', 'encode');
		$content = get_str('content', '');
		if ($do == 'encode'){
			output(urlencode($content));
		}else{
			output(urldecode($content));
		}
		break;

	case 'base64':
		$do = get_str('do', 'encode');
		$content = get_str('content', '');
		if ($do == 'encode'){
			output(base64_encode($content));
		}else{
			output(base64_decode($content));
		}
		break;

	default:
		output('Parameters Error!');
}
output();


function output($result = false){
	if ($result !== false){
		echo json_encode($result);
	}
	exit;
}
